package com.shop.loan.proxy;

import com.shop.loan.model.Goods;
import com.shop.loan.model.GoodsSize;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.DataProxy;

import java.math.BigDecimal;

@Service
public class GoodsDataProxy implements DataProxy<Goods> {

    @Override
    public void beforeAdd(Goods goods) {
        setGoodsInfo(goods);
    }

    @Override
    public void beforeUpdate(Goods goods) {
        setGoodsInfo(goods);
    }


    public void setGoodsInfo(Goods goods) {
        if (goods.getGoodsSizes() == null) {
            return;
        }

        BigDecimal minMoney = BigDecimal.ZERO;
        Integer stockSum = 0;
        Integer rentalStockSum = 0;
        for (GoodsSize goodsSize : goods.getGoodsSizes()) {
            goodsSize.setGoodsId(goods.getId());

            stockSum = stockSum + goodsSize.getStock();
            rentalStockSum = rentalStockSum + goodsSize.getRentalStock();

            if (minMoney.compareTo(BigDecimal.ZERO) == 0) {
                minMoney = goodsSize.getPrice();
            } else if (minMoney.compareTo(goodsSize.getPrice()) > 0) {
                minMoney = goodsSize.getPrice();
            }
        }
        goods.setTotalStock(stockSum);
        goods.setRentalStock(rentalStockSum);
    }
}
